<template>
<div>
  <!--  面包屑导航-->
  <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    <el-breadcrumb-item>添加商品</el-breadcrumb-item>
  </el-breadcrumb>
  <el-card>
<!--    alter 警告-->
    <el-alert
      :closable = 'false'
      title="添加商品信息"
      type="info"
      center
      show-icon>
    </el-alert>
<!--    步骤条-->
    <el-steps :space="200" :active="numberActiveName" finish-status="success" align-center>
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>
<!--  tab标签页-->
    <el-form :model="addGoodsForm" :rules="addGoodsFormRules" ref="addGoodsFormRuleForm" label-width="100px" label-position="top">
    <el-tabs @tab-click="tabClicked" tab-position="left" v-model="activeName" :before-leave="beforeTabLeave">
      <el-tab-pane label="基本信息" name="0">
        <el-form-item label="商品名称" prop="goods_name">
          <el-input v-model="addGoodsForm.goods_name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="goods_price">
          <el-input v-model="addGoodsForm.goods_price" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品重量" prop="goods_weight">
          <el-input v-model="addGoodsForm.goods_weight" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="goods_number">
          <el-input v-model="addGoodsForm.goods_number" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="goods_cat">
          <el-cascader
            expand-trigger="hover"
            v-model="addGoodsForm.goods_cat"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"></el-cascader>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="商品参数" name="1">
        <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
          <el-checkbox-group v-model="item.attr_vals">
            <el-checkbox border :label="item2" v-for="(item2,index) in item.attr_vals" :key="index"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="商品属性" name="2">
        <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
          <el-input v-model="item.attr_vals"></el-input>
        </el-form-item>
      </el-tab-pane>
      <el-tab-pane label="商品图片" name="3">
        <el-upload
          class="upload-demo"
          :action="actionUrl"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          list-type="picture"
          :headers="headerObj"
          :on-success="handleSuccess"
        >
          <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
      </el-tab-pane>
      <el-tab-pane label="商品内容" name="4">
<!--        富文本编辑器-->
        <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
<!--      添加商品按钮-->
        <el-button type="primary" class="addGoodsBtn" @click="addGoods">添加商品</el-button>
      </el-tab-pane>
    </el-tabs>
    </el-form>
  </el-card>
<!--  图片预览对话框-->
  <el-dialog
    title="提示"
    :visible.sync="fileDialogVisible"
    width="50%">
    <img :src="previewUrl" width="100%">
  </el-dialog>
</div>
</template>

<script>
import _ from 'lodash'
export default {
  name: 'addgoods',
  data () {
    return {
      activeName: '0',
      // 添加商品表单数据
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 表单数据验证
      addGoodsFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
      },
      // 商品分类数据
      cateList: [],
      // 级联选择器的配置信息
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 商品动态参数数据
      manyTableData: [],
      // 商品静态属性数据
      onlyTableData: [],
      // 图片上传地址
      actionUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 设置图片上传请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览地址
      previewUrl: '',
      // 图片预览对话框
      fileDialogVisible: false
    }
  },
  computed: {
    numberActiveName () {
      return this.activeName - 0
    },
    cateId () {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data } = await this.$axios.get('categories')
      if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
      this.cateList = data.data
    },
    // 级联选择器选择触发事件
    handleChange () {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },
    // 基本信息验证不通过不能跳转到下一列
    beforeTabLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请完善基本信息中的商品分类')
        return false
      }
    },
    // tabs点击时后触发
    async tabClicked () {
      if (this.activeName === '1') {
        // 代表选择了商品动态参数
        const { data } = await this.$axios.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
        data.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.manyTableData = data.data
      } else if (this.activeName === '2') {
        // 代表选择了商品静态属性
        const { data } = await this.$axios.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        if (data.meta.status !== 200) return this.$message.error(data.meta.msg)
        data.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        })
        this.onlyTableData = data.data
      }
    },
    //  触发图片预览函数
    handlePreview (file) {
      this.previewUrl = file.response.data.url
      this.fileDialogVisible = true
      console.log(this.previewUrl)
    },
    // 删除图片触发函数
    handleRemove (file) {
      // 获取将要删除图片的临时路径
      const filePath = file.response.data.tmp_path
      // 从addGoodsForm.pics数组中找到对应路径的index
      const i = this.addGoodsForm.pics.findIndex(x => x.pic === filePath)
      this.addGoodsForm.pics.splice(i, 1)
      console.log(this.addGoodsForm)
    },
    // 图片上传成功后触发的钩子
    handleSuccess (response) {
      const picInfo = {
        pic: response.data.tmp_path
      }
      this.addGoodsForm.pics.push(picInfo)
    },
    // 添加商品
    addGoods () {
      this.$refs.addGoodsFormRuleForm.validate(async bool => {
        if (!bool) {
          this.$message.error('表单预验证失败')
        }
        const formData = _.cloneDeep(this.addGoodsForm)
        formData.goods_cat = formData.goods_cat.join(',')
        // 处理动态参数
        this.manyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_vals: item.attr_vals.join(' ') }
          this.addGoodsForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_vals: item.attr_vals }
          this.addGoodsForm.attrs.push(newInfo)
        })
        formData.attrs = this.addGoodsForm.attrs
        const { data } = await this.$axios.post('goods', formData)
        if (data.meta.status !== 201) return this.$message.error(data.meta.msg)
        this.$message.success(data.meta.msg)
        this.$router.push('/home/goods')
      })
    }
  }
}
</script>

<style scoped>
.el-tabs{
  margin-top: 15px;
}
.el-checkbox{
  margin:5px 10px 0 0 !important;
}
.addGoodsBtn{
  margin-top: 15px;
}
</style>
